// Copyright 2017 The Closure Rules Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package io.bazel.rules.closure.http;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableSet;
import java.net.URI;

/** HTTP request message. */
public final class HttpRequest extends HttpMessage<HttpRequest> {

  private static final ImmutableSet<String> NO_PAYLOAD_METHODS =
      ImmutableSet.of("GET", "HEAD", "DELETE", "CONNECT", "TRACE");

  private URI uri = URI.create("/");

  public URI getUri() {
    return uri;
  }

  public HttpRequest setUri(URI uri) {
    this.uri = checkNotNull(uri);
    return this;
  }

  public HttpResponse newResponse() {
    return new HttpResponse()
        .setMethod(getMethod())
        .setVersion(getVersion())
        .setHeader("Connection", getHeader("Connection"));
  }

  @Override
  boolean isPayloadAllowed() {
    return !NO_PAYLOAD_METHODS.contains(getMethod());
  }

  @Override
  void generateFirstLineOfMessage(StringBuilder builder) {
    builder.append(getMethod());
    builder.append(' ');
    builder.append(uri);
    builder.append(' ');
    builder.append(getVersion());
    builder.append("\r\n");
  }
}
